package com.toolbox.handler;

import com.alibaba.fastjson2.JSONObject;
import com.toolbox.exceptionhandler.DataException;
import com.toolbox.exceptionhandler.RightException;
import com.toolbox.exceptionhandler.ServerException;
import com.toolbox.result.ResponseResultDTO;
import org.apache.commons.io.IOUtils;
import org.apache.tomcat.util.http.fileupload.impl.FileSizeLimitExceededException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.bind.support.WebExchangeBindException;

import javax.servlet.http.HttpServletRequest;
import java.net.URLDecoder;

import static com.toolbox.enums.ResponseStatusEnum.FILE_SIZE_LIMIT_EXCEEDED;
import static com.toolbox.enums.ResponseStatusEnum.HTTP_REQUEST_METHOD_NOT_SUPPORTED_EXCEPTION;
import static com.toolbox.enums.ResponseStatusEnum.NO_PERMISSION;
import static com.toolbox.enums.ResponseStatusEnum.NULL_POINTER_EXCEPTION;
import static com.toolbox.enums.ResponseStatusEnum.NUMBER_FORMAT_EXCEPTION;

/**
 * <p>
 * Description：
 * </p>
 *
 * @author Mango
 * @version v1.0.0
 * @date 2023-11-18 10:48
 * @see com.toolbox.handler
 */
@SuppressWarnings("ALL")
@RestControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
    private static final Logger bizLogger = LoggerFactory.getLogger("bizErrorLogger");

    /**
     * Exception
     *
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    public ResponseResultDTO<Void> handleException(HttpServletRequest req, Exception e) {
        loggerUrl(req, bizLogger, e.getMessage());
        return ResponseResultDTO.error(null, e.getMessage());
    }

    /**
     * 系统运行时异常
     *
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(RuntimeException.class)
    public ResponseResultDTO<Void> handleRuntimeException(HttpServletRequest req, RuntimeException e) {
        loggerUrl(req, bizLogger, e.getMessage());
        return ResponseResultDTO.error(null, e.getMessage());
    }

    /**
     * 表示一般的数据异常
     *
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(DataException.class)
    public ResponseResultDTO<Void> handleDataException(HttpServletRequest req, DataException e) {
        loggerUrl(req, bizLogger, e.getMessage());
        return ResponseResultDTO.error(null, e.getMessage());
    }

    /**
     * 权限异常 如用户的权限不足 不打印堆栈
     *
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(RightException.class)
    public ResponseResultDTO<Void> handleRightException(HttpServletRequest req, RightException e) {
        loggerUrl(req, bizLogger, NO_PERMISSION.getDetails());
        return ResponseResultDTO.unSuccess(NO_PERMISSION);
    }

    /**
     * 表示服务器异常
     *
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(ServerException.class)
    public ResponseResultDTO<Void> handleServerException(HttpServletRequest req, ServerException e) {
        loggerUrl(req, bizLogger, e.getMessage());
        return ResponseResultDTO.error(null, e.getMessage());
    }

    /**
     * 空指针异常
     *
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(NullPointerException.class)
    public ResponseResultDTO<Void> handleNullPointerException(HttpServletRequest req, NullPointerException e) {
        loggerUrl(req, bizLogger, NULL_POINTER_EXCEPTION.getDetails());
        return ResponseResultDTO.unSuccess(NULL_POINTER_EXCEPTION);
    }

    /**
     * 方法参数校验
     *
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseResultDTO<Void> handleMethodArgumentNotValidException(HttpServletRequest req, MethodArgumentNotValidException e) {
        loggerUrl(req, bizLogger, e.getBindingResult().getFieldError().getDefaultMessage());
        return ResponseResultDTO.error(null, e.getBindingResult().getFieldError().getDefaultMessage());
    }

    /**
     * 方法参数校验
     *
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(WebExchangeBindException.class)
    public ResponseResultDTO<Void> handleWebExchangeBindException(HttpServletRequest req, WebExchangeBindException e) {
        loggerUrl(req, bizLogger, e.getBindingResult().getFieldError().getDefaultMessage());
        return ResponseResultDTO.error(null, e.getBindingResult().getFieldError().getDefaultMessage());
    }

    /**
     * 数字格式错误
     *
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(NumberFormatException.class)
    public ResponseResultDTO<Void> handleNumberFormatException(HttpServletRequest req, NumberFormatException e) {
        loggerUrl(req, bizLogger, NUMBER_FORMAT_EXCEPTION.getDetails());
        return ResponseResultDTO.unSuccess(NUMBER_FORMAT_EXCEPTION);
    }

    /**
     * FileSizeLimitExceededException
     *
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(FileSizeLimitExceededException.class)
    public ResponseResultDTO<Void> handleFileSizeLimitExceededException(HttpServletRequest req, FileSizeLimitExceededException e) {
        loggerUrl(req, bizLogger, FILE_SIZE_LIMIT_EXCEEDED.getDetails());
        return ResponseResultDTO.unSuccess(FILE_SIZE_LIMIT_EXCEEDED);
    }

    /**
     * 请求方式异常
     *
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public ResponseResultDTO<Void> handleHttpRequestMethodNotSupportedException(HttpServletRequest req, HttpRequestMethodNotSupportedException e) {
        loggerUrl(req, bizLogger, HTTP_REQUEST_METHOD_NOT_SUPPORTED_EXCEPTION.getDetails());
        return ResponseResultDTO.unSuccess(HTTP_REQUEST_METHOD_NOT_SUPPORTED_EXCEPTION);
    }

    /**
     * 统一错误日志处理
     *
     * @param request 请求
     * @param logger  日志
     * @param message 提示语
     */
    private void loggerUrl(HttpServletRequest request, Logger logger, String message) {
        String url = request.getRequestURL().toString();
        try {
            url = URLDecoder.decode(url, "utf-8");
        } catch (Throwable e) {
            logger.error("decode_error_url=" + url, e);
        }

        StringBuilder sb = new StringBuilder();
        sb.append(IOUtils.LINE_SEPARATOR).append("    requestUrl=").append(url);
        sb.append(IOUtils.LINE_SEPARATOR).append("    requestParam=").append(JSONObject.toJSONString(request.getParameterMap()));
        sb.append(IOUtils.LINE_SEPARATOR).append("    errorMessage=").append(message);
        logger.error(sb.toString());
    }

}
